<template>
	<view class="chat">
		<scroll-view :style="{height: `${windowHeight-inputHeight}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" :scroll-with-animation="true" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<view style="font-size: 30rpx; display: flex; justify-content: center;">来自漂流瓶：{{paperContent}}</view>
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.senderId === currentUser.uuid">
						<!-- 文字内容 -->
						<view class="content right">
							{{item.payload.text}}
						</view>
						<!-- 头像 -->
						<view class="avatar">
							<image :src="currentUser.avatar" mode="widthFix"></image>
						</view>
					</view>
					<!-- 好友发的消息 -->
					<view class="item Ai" v-if="item.senderId === friend.uuid">
						<!-- 头像 -->
						<view class="avatar">
							<image :src="friend.avatar" mode="widthFix"></image>
						</view>
						<!-- 文字内容 -->
						<view class="content left">
							{{item.payload.text}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea">
					<!-- <textarea v-model="chatMsg" maxlength="300" :show-confirm-bar="false" auto-height></textarea> -->
					<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
						:show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight" @focus="focus"
						@blur="blur" auto-height></textarea>

				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	import GoEasy from 'goeasy';
	import {
		getPaperContent
	} from '../../api/login';
	export default {
		data() {
			return {
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				//发送的消息
				chatMsg: "",
				paperContent: '',
				msgList: [],
				currentUser: {},
				friend: {
					uuid: '',
					avatar: '',
					username: '',
					gender: 0
				}
			}
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				console.log("bottomHeight:", this.bottomHeight)
				console.log("keyboardHeight", this.keyboardHeight)
				return this.bottomHeight + this.keyboardHeight
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		onLoad: function(option) {
			// uni.onKeyboardHeightChange(res => {
			// 	//这里正常来讲代码直接写
			// 	//this.keyboardHeight=this.rpxTopx(res.height)就行了
			// 	//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
			// 	this.keyboardHeight = this.rpxTopx(res.height - 30)
			// 	if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			// })

			const item = JSON.parse(decodeURIComponent(option.item));
			console.log("这是item", item)
			if (item) {
				this.friend.uuid = uni.getStorageSync("uuid") === item.lastMessage.senderId ? item.lastMessage
					.receiverId : item.lastMessage.senderId
				this.friend.avatar = item.data.avatar
				this.friend.username = item.data.nickname
				uni.setNavigationBarTitle({
					title: item.data.nickname ? item.data.nickname : "抖音用户"
				});
				getPaperContent({
					sender_uuid: this.friend.uuid,
					accept_id: uni.getStorageSync("userId")
				}).then(res => {
					this.paperContent = res.data
					this.paperContent = this.truncateString(res.data, 25)
				}).catch(err => {
					this.paperContent = ''
					console.log("获取两人之间的漂流瓶错误", err)
				})
			}
			this.currentUser = uni.getStorageSync("userInfo")

			//获取历史消息
			this.getHistoryMessage()
			let that = this
			var onMessageReceived = function(message) {
				let senderId = message.senderId
				let receiverId = message.receiverId
				let friendId = uni.getStorageSync("uuid") === senderId ? receiverId : senderId
				if (friendId === that.friend.uuid) {
					that.msgList.push(message)
					//聊天时收到消息标记为已读
					//收到消息时滚动到最底部
					that.scrollToBottom
				}
			};
			//监听和接收单聊消息
			this.goEasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onMessageReceived);
			//标记消息为已读
			this.goEasy.im.markMessageAsRead({
				id: that.friend.uuid,
				type: GoEasy.IM_SCENE.PRIVATE, //群聊：GoEasy.IM_SCENE.GROUP, 客服消息：GoEasy.IM_SCENE.CS,
				onSuccess: function() {
					console.log('标记私聊已读成功');
				},
				onFailed: function(error) {
					console.log('标记私聊已读失败', error);
				},
			});
		},
		onUnload() {
			let that = this
			var onMessageReceived = function(message) {
				let senderId = message.senderId
				let receiverId = message.receiverId
				let friendId = uni.getStorageSync("uuid") === senderId ? receiverId : senderId
				if (friendId === that.friend.uuid) {
					that.msgList.push(message)
					//聊天时收到消息标记为已读
					//收到消息时滚动到最底部
					that.scrollToBottom
				}
			};
			// 取消监听
			this.goEasy.im.off(GoEasy.IM_EVENT.MESSAGE_DELETED, onMessageReceived);
		},
		methods: {
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},

			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},

			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},

			//字符串超过指定长度用省略号显示
			truncateString(str, maxLength) {
				if (str.length <= maxLength) {
					return str;
				} else {
					return str.substring(0, maxLength - 1) + '...';
				}
			},

			isEmpty(input) {
				return input === null || input === undefined || input === '';
			},
			//获取历史消息
			getHistoryMessage() {
				let that = this
				this.goEasy.im.history({
					id: that.friend.uuid,
					type: GoEasy.IM_SCENE.PRIVATE,
					lastTimestamp: null, //上次查询结果里最后一条消息的时间戳，首次查询传入null即可
					limit: 30, //可选项，返回的消息条数，默认为10条，最多30条
					onSuccess: function(result) {
						that.msgList = result.content
					},
					onFailed: function(error) { //获取失败
						console.log("Failed to query private message, code:" + error.code + " content:" + error
							.content);
					},
				})
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				if (!this.isEmpty(this.chatMsg)) {
					let that = this
					//goEasy发送消息
					var im = this.goEasy.im
					//创建消息, 内容最长不超过3K，可以发送字符串，对象和json格式字符串
					let textMessage = im.createTextMessage({
						text: this.chatMsg, //消息内容
						to: {
							type: GoEasy.IM_SCENE.PRIVATE, //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
							id: that.friend.uuid, //接收方用户id
							data: {
								"avatar": that.friend.avatar,
								"nickname": that.friend.username
							} //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
						}
					});

					//发送消息
					im.sendMessage({
						message: textMessage,
						onSuccess: function(message) { //发送成功
							console.log("Private message sent successfully.", message);
							that.msgList.push(message) //todo:这个地方不用push吧
						},
						onFailed: function(error) { //发送失败
							console.log('Failed to send private message，code:' + error.code + ' ,error ' +
								error.content);
						}
					});
					this.chatMsg = '';
				} else {
					uni.showToast({
						title: "不能发送空白消息",
						icon: 'none',
						duration: 1000
					})
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #F6F6F6;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					// 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

					.content {
						position: relative;
						max-width: 486rpx;
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}

					.avatar {
						display: flex;
						justify-content: center;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 8rpx;
						overflow: hidden;

						image {
							align-self: center;
						}

					}
				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 177rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;


			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 30rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #EDEDED;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				padding-bottom: 70rpx;

				textarea {
					width: 537rpx;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #FFFFFF;
					border-radius: 8rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 43rpx;
					padding: 5rpx 8rpx;
				}
			}

			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 70rpx;
				margin-left: 25rpx;
				width: 128rpx;
				height: 75rpx;
				background: $sendBtnbgc;
				border-radius: 8rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
		}
	}
</style>